package com.mashibing.disruptor.v1;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.YieldingWaitStrategy;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import java.nio.ByteBuffer;
import java.time.LocalTime;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class Main1 {
    // 单生产者单消费者
    public static void main(String[] args) throws InterruptedException {

        Disruptor<LongEvent> disruptor = new Disruptor<>(new LongEventFactory(), 1024,
                Executors.defaultThreadFactory(), ProducerType.SINGLE, new YieldingWaitStrategy());

        // 多个EventHandler并发执行
        disruptor.handleEventsWith(new LongEventHandler1(), (event, sequence, endOfBatch) ->
                System.out.printf("\033[32m %s ===>> %s ===>> lambdaEventHandler2 ===>> %s \033[0m\n",
                        Thread.currentThread().getName(), LocalTime.now(), event.getValue()));

        disruptor.start();

        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

//        LongEventProducer1 producer1 = new LongEventProducer1(ringBuffer);
        LongEventProducer2 producer2 = new LongEventProducer2(ringBuffer);

        ByteBuffer bb = ByteBuffer.allocate(8);

        for(long l = 0; l<10; l++) {
            bb.putLong(0, l);
//            producer2.onData(bb);
            producer2.onData(bb, 1000L);

            TimeUnit.MILLISECONDS.sleep(1000);
        }

        disruptor.shutdown();
    }
}
